<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>区块链资产管理平台</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background-color: #f5f7fa;
        }
        .chaincode-container {
            max-width: 1200px;
            margin: 20px auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .chaincode-header {
            background-color: #2c3e50;
            color: white;
            padding: 15px 20px;
        }
        .nav-tabs {
            background-color: #f8f9fa;
            padding-left: 20px;
        }
        .tab-content {
            padding: 20px;
        }
        .operation-card {
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            border: 1px solid #eee;
        }
        .operation-header {
            background-color: #f8f9fa;
            padding: 10px 15px;
            border-bottom: 1px solid #eee;
            font-weight: bold;
        }
        .operation-body {
            padding: 15px;
        }
        .asset-card {
            border-left: 4px solid #3498db;
            margin-bottom: 15px;
        }
        .log-entry {
            font-family: monospace;
            font-size: 13px;
            padding: 5px 0;
            border-bottom: 1px solid #f0f0f0;
        }
    </style>
</head>
<body>
    <div class="chaincode-container">
        <div class="chaincode-header">
            <h4>区块链资产管理平台</h4>
            <p class="mb-0">基于Hyperledger Fabric的资产链码管理系统</p>
        </div>
        
        <ul class="nav nav-tabs" id="chaincodeTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="assets-tab" data-bs-toggle="tab" data-bs-target="#assets" type="button" role="tab">资产管理</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="logs-tab" data-bs-toggle="tab" data-bs-target="#logs" type="button" role="tab">操作日志</button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="code-tab" data-bs-toggle="tab" data-bs-target="#code" type="button" role="tab">链码查看</button>
            </li>
        </ul>
        
        <div class="tab-content" id="chaincodeTabContent">
            <!-- 资产管理标签页 -->
            <div class="tab-pane fade show active" id="assets" role="tabpanel">
                <div class="row">
                    <div class="col-md-4">
                        <div class="operation-card">
                            <div class="operation-header">创建资产</div>
                            <div class="operation-body">
                                <form id="createAssetForm">
                                    <div class="mb-3">
                                        <label for="assetId" class="form-label">资产ID</label>
                                        <input type="text" class="form-control" id="assetId" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="assetOwner" class="form-label">所有者</label>
                                        <input type="text" class="form-control" id="assetOwner" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="assetName" class="form-label">资产名称</label>
                                        <input type="text" class="form-control" id="assetName" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="assetInfo" class="form-label">资产信息</label>
                                        <textarea class="form-control" id="assetInfo" rows="3"></textarea>
                                    </div>
                                    <button type="submit" class="btn btn-primary">创建</button>
                                </form>
                            </div>
                        </div>
                        
                        <div class="operation-card">
                            <div class="operation-header">转移资产</div>
                            <div class="operation-body">
                                <form id="transferAssetForm">
                                    <div class="mb-3">
                                        <label for="transferId" class="form-label">资产ID</label>
                                        <input type="text" class="form-control" id="transferId" required>
                                    </div>
                                    <div class="mb-3">
                                        <label for="newOwner" class="form-label">新所有者</label>
                                        <input type="text" class="form-control" id="newOwner" required>
                                    </div>
                                    <button type="submit" class="btn btn-warning">转移</button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-8">
                        <div class="operation-card">
                            <div class="operation-header">查询资产</div>
                            <div class="operation-body">
                                <div class="input-group mb-3">
                                    <input type="text" class="form-control" id="queryId" placeholder="输入资产ID">
                                    <button class="btn btn-outline-secondary" type="button" id="queryAssetBtn">查询</button>
                                </div>
                                
                                <div id="assetResult" class="d-none">
                                    <div class="card asset-card">
                                        <div class="card-body">
                                            <h5 class="card-title" id="resultName">资产名称</h5>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <p class="mb-1"><strong>ID:</strong> <span id="resultId"></span></p>
                                                    <p class="mb-1"><strong>所有者:</strong> <span id="resultOwner"></span></p>
                                                </div>
                                                <div class="col-md-6">
                                                    <p class="mb-1"><strong>信息:</strong> <span id="resultInfo"></span></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div id="assetNotFound" class="alert alert-warning d-none">
                                    未找到该资产
                                </div>
                            </div>
                        </div>
                        
                        <div class="operation-card">
                            <div class="operation-header">资产列表</div>
                            <div class="operation-body">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>名称</th>
                                            <th>所有者</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="assetList">
                                        <!-- 资产列表将通过JavaScript动态加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 操作日志标签页 -->
            <div class="tab-pane fade" id="logs" role="tabpanel">
                <div class="operation-card">
                    <div class="operation-header">链码操作日志</div>
                    <div class="operation-body">
                        <div id="logContainer">
                            <div class="log-entry">2023-05-20 10:30:15 | 系统初始化完成</div>
                            <!-- 日志将通过JavaScript动态添加 -->
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 链码查看标签页 -->
            <div class="tab-pane fade" id="code" role="tabpanel">
                <div class="operation-card">
                    <div class="operation-header">链码源代码</div>
                    <div class="operation-body">
                        <pre><code id="chaincodeSource">// 链码源代码将在这里显示</code></pre>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 这里将添加JavaScript交互逻辑
        document.addEventListener('DOMContentLoaded', function() {
            // 显示链码源代码
            const chaincodeSource = `package main

import (
    "encoding/json"
    "fmt"
    "github.com/hyperledger/fabric-contract-api-go/contractapi"
)

type SmartContract struct {
    contractapi.Contract
}

type Asset struct {
    ID    string \`json:"id"\`
    Owner string \`json:"owner"\`
    Name  string \`json:"name"\`
    Info  string \`json:"info"\`
}

/*
资产上链
*/
func (s *SmartContract) Create(ctx contractapi.TransactionContextInterface, id string, owner string, name string, info string) (string, error) {
    //将数据保存在账本中
    asset := Asset{ID: id, Owner: owner, Name: name, Info: info}
    kvBytes, _ := json.Marshal(asset)
    err := ctx.GetStub().PutState(id, kvBytes)
    if err != nil {
        return "", fmt.Errorf("Failed to set asset: %s", err.Error())
    }
    return id, nil
}

/*
查询资产
*/
func (s *SmartContract) Query(ctx contractapi.TransactionContextInterface, id string) (*Asset, error) {
    //通过key，从账本中获取数据
    kvBytes, err := ctx.GetStub().GetState(id)
    if err != nil {
        return nil, fmt.Errorf("Failed to read from world state. %s", err.Error())
    }
    if kvBytes == nil {
        return nil, fmt.Errorf("%s does not exist", id)
    }
    kv := new(Asset)
    _ = json.Unmarshal(kvBytes, kv)
    return kv, nil
}

/*
转移资产
*/
func (s *SmartContract) Transfer(ctx contractapi.TransactionContextInterface, id string, owner string) error {
    //通过key，从账本中获取数据
    kvBytes, err := ctx.GetStub().GetState(id)
    if err != nil {
        return fmt.Errorf("Failed to read from world state. %s", err.Error())
    }
    if kvBytes == nil {
        return fmt.Errorf("%s does not exist", id)
    }
    asset := new(Asset)
    _ = json.Unmarshal(kvBytes, asset)
    asset.Owner = owner
    assetBytes, _ := json.Marshal(asset)
    err = ctx.GetStub().PutState(id, assetBytes)
    if err != nil {
        return fmt.Errorf("Failed to set asset: %s", err.Error())
    }
    return nil
}

func main() {
    chaincode, err := contractapi.NewChaincode(new(SmartContract))
    if err != nil {
        fmt.Printf("Error create fabcar chaincode: %s", err.Error())
        return
    }
    if err := chaincode.Start(); err != nil {
        fmt.Printf("Error starting fabcar chaincode: %s", err.Error())
    }
}`;
            document.getElementById('chaincodeSource').textContent = chaincodeSource;

            // 模拟资产数据
            const mockAssets = [
                { id: "asset001", owner: "user1", name: "数字艺术品", info: "限量版数字艺术品" },
                { id: "asset002", owner: "user2", name: "房地产契约", info: "北京市朝阳区某处房产" },
                { id: "asset003", owner: "user3", name: "专利证书", info: "新型技术专利" }
            ];

            // 渲染资产列表
            function renderAssetList() {
                const assetList = document.getElementById('assetList');
                assetList.innerHTML = '';
                
                mockAssets.forEach(asset => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${asset.id}</td>
                        <td>${asset.name}</td>
                        <td>${asset.owner}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary view-asset" data-id="${asset.id}">查看</button>
                        </td>
                    `;
                    assetList.appendChild(row);
                });
                
                // 添加查看按钮事件
                document.querySelectorAll('.view-asset').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const assetId = this.getAttribute('data-id');
                        queryAsset(assetId);
                    });
                });
            }
            
            // 查询资产
            function queryAsset(assetId) {
                // 在实际应用中，这里应该调用链码的Query方法
                const asset = mockAssets.find(a => a.id === assetId);
                
                if (asset) {
                    document.getElementById('resultId').textContent = asset.id;
                    document.getElementById('resultName').textContent = asset.name;
                    document.getElementById('resultOwner').textContent = asset.owner;
                    document.getElementById('resultInfo').textContent = asset.info;
                    
                    document.getElementById('assetResult').classList.remove('d-none');
                    document.getElementById('assetNotFound').classList.add('d-none');
                    
                    // 添加到日志
                    addLog(`查询资产: ${assetId}`);
                } else {
                    document.getElementById('assetResult').classList.add('d-none');
                    document.getElementById('assetNotFound').classList.remove('d-none');
                    
                    // 添加到日志
                    addLog(`查询资产失败: ${assetId} 不存在`);
                }
                
                // 滚动到结果区域
                document.getElementById('assetResult').scrollIntoView({ behavior: 'smooth' });
            }
            
            // 添加日志
            function addLog(message) {
                const now = new Date();
                const timestamp = now.toISOString().replace('T', ' ').substring(0, 19);
                const logEntry = document.createElement('div');
                logEntry.className = 'log-entry';
                logEntry.textContent = `${timestamp} | ${message}`;
                document.getElementById('logContainer').prepend(logEntry);
            }
            
            // 初始化资产列表
            renderAssetList();
            
            // 查询按钮事件
            document.getElementById('queryAssetBtn').addEventListener('click', function() {
                const assetId = document.getElementById('queryId').value;
                if (assetId) {
                    queryAsset(assetId);
                }
            });
            
            // 创建资产表单提交
            document.getElementById('createAssetForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const assetId = document.getElementById('assetId').value;
                const owner = document.getElementById('assetOwner').value;
                const name = document.getElementById('assetName').value;
                const info = document.getElementById('assetInfo').value;
                
                // 在实际应用中，这里应该调用链码的Create方法
                mockAssets.push({
                    id: assetId,
                    owner: owner,
                    name: name,
                    info: info
                });
                
                // 重新渲染列表
                renderAssetList();
                
                // 清空表单
                this.reset();
                
                // 添加到日志
                addLog(`创建资产: ${assetId} (${name})`);
                
                // 显示成功消息
                alert('资产创建成功！');
            });
            
            // 转移资产表单提交
            document.getElementById('transferAssetForm').addEventListener('submit', function(e) {
                e.preventDefault();
                
                const assetId = document.getElementById('transferId').value;
                const newOwner = document.getElementById('newOwner').value;
                
                // 在实际应用中，这里应该调用链码的Transfer方法
                const assetIndex = mockAssets.findIndex(a => a.id === assetId);
                
                if (assetIndex !== -1) {
                    const oldOwner = mockAssets[assetIndex].owner;
                    mockAssets[assetIndex].owner = newOwner;
                    
                    // 重新渲染列表
                    renderAssetList();
                    
                    // 清空表单
                    this.reset();
                    
                    // 添加到日志
                    addLog(`转移资产: ${assetId} 从 ${oldOwner} 到 ${newOwner}`);
                    
                    // 显示成功消息
                    alert('资产转移成功！');
                } else {
                    // 添加到日志
                    addLog(`转移资产失败: ${assetId} 不存在`);
                    
                    alert('资产不存在！');
                }
            });
        });
    </script>
</body>
</html>